package com.vip.jwt.config;

import com.vip.jwt.common.cache.RedisCacheManager;
import com.vip.jwt.common.manager.RedisManager;
import com.vip.jwt.common.utils.FileUtil;
import com.vip.jwt.common.utils.JwtUtil;
import com.vip.jwt.common.utils.RedisUtil;
import lombok.Getter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.Filter;
import java.util.*;

@Configuration
@AutoConfigureAfter(ShiroLifecycleAutoConfiguration.class)
@ConditionalOnClass(RedisAutoConfiguration.class)
public class ShiroConfig {

    /**
     * Redis过期时间
     */
    private final static Integer REDIS_EXPIRE_DATA = 12 * 60 * 60 * 1000;

    @Getter
    private static String MODULE_NAME;

    @Value("${module-name}")
    public void setModuleName(String moduleName) {
        MODULE_NAME = moduleName;
    }

    private final
    RedisTemplate<String, Object> redisTemplate;

    public ShiroConfig(@Qualifier("redisTemplateObj") RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 将Jwt工具注册为组件
     * @return
     */
    @Bean
    public JwtUtil jwtUtil(){
        return new JwtUtil(cacheManager());
    }

    /**
     * 缓存管理器
     * @return
     */
    @Bean
    public CacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        redisCacheManager.setCacheKey(MODULE_NAME);
        redisCacheManager.setExpire(REDIS_EXPIRE_DATA);
        return redisCacheManager;
    }

    /**
     * Redis管理器
     * @return
     */
    @Bean
    public RedisManager redisManager() {
        return new RedisManager(redisTemplate);
    }

    /**
     * 配置Shiro工厂Bean
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean factoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        //这里添加自己的过滤器
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JwtFilter());
        factoryBean.setFilters(filterMap);

        //拦截器（注意这里必须使用LinkedHashMap）
        Map<String,String> filterRuleMap = new LinkedHashMap<>();

        /**
         * 放行Url
         */
        //二维码
        filterRuleMap.put("/api/images/captcha", "anon");
        filterRuleMap.put("/apk/*", "anon");
        filterRuleMap.put("/api/login","anon");
        filterRuleMap.put("/api/login/**","anon");
        filterRuleMap.put("/api/test","anon");
        filterRuleMap.put("/api/test/**","anon");
        filterRuleMap.put("/api/app/version","anon");
        filterRuleMap.put("/api/file/upload/**", "anon");
        filterRuleMap.put("/api/file/downLoad/**", "anon");
        filterRuleMap.put("/api/xcx/**","anon");
        //WebSocket
        filterRuleMap.put("/websocket/**", "anon");
        //支付回调接口
        filterRuleMap.put("/api/callback/wx","anon");
        filterRuleMap.put("/api/callback/wx/refund","anon");
        filterRuleMap.put("/api/callback/zfb","anon");
        filterRuleMap.put("/api/callback/tx/receive","anon");
        //Swagger2
        filterRuleMap.put("/swagger-ui.html", "anon");
        filterRuleMap.put("/swagger-resources", "anon");
        filterRuleMap.put("/swagger-resources/configuration/security", "anon");
        filterRuleMap.put("/swagger-resources/configuration/ui", "anon");
        filterRuleMap.put("/v2/api-docs", "anon");
        filterRuleMap.put("/webjars/springfox-swagger-ui/**", "anon");
        //Druid阿里云数据库连接池
        filterRuleMap.put("/druid/**", "anon");
        //静态资源文件
        filterRuleMap.put("/webjars/**", "anon");
        filterRuleMap.put("/css/**", "anon");
        filterRuleMap.put("/fonts/**", "anon");
        filterRuleMap.put("/img/**", "anon");
        filterRuleMap.put("/js/**", "anon");
        filterRuleMap.put("/favicon.ico", "anon");

        //根据后缀名放行
        //filterRuleMap.put("/**/*.jpg", "anon");
        //filterRuleMap.put("/**/*.png", "anon");
        //以前缀放行静态文件(前缀：项目名)
        filterRuleMap.put("/"+MODULE_NAME+"/**","anon");

        filterRuleMap.put("/**","jwt");
        //filterRuleMap.put("/**","authc");

        factoryBean.setFilterChainDefinitionMap(filterRuleMap);
        return factoryBean;
    }

    /**
     * 权限管理，配置主要是Realm的管理认证
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置多realm.
        securityManager.setAuthenticator(modularRealmAuthenticator());
        List<Realm> realms = new ArrayList<>();
        realms.add(myRealm());
        realms.add(xcxRealm());
        //使用自己的Relam
        securityManager.setRealms(realms);
        //关闭Shiro的Session功能
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        //不创建Session
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        return securityManager;
    }

    /**
     * 自己的Realm
     * @return
     */
    @Bean
    public MyRealm myRealm(){
        MyRealm myRealm = new MyRealm();
        //给自己的Realm设置凭证
        //myRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myRealm;
    }

    /**
     * 小程序Realm
     * @return
     */
    @Bean
    public XCXRealm xcxRealm(){
        XCXRealm xcxRealm = new XCXRealm();
        //xcxRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return xcxRealm;
    }

    /**
     * 凭证匹配器
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }

    /**
     * 系统自带的Realm管理，主要针对多realm
     */
    @Bean
    public ModularRealmAuthenticator modularRealmAuthenticator(){
        //自己重写的ModularRealmAuthenticator
        MyModularRealmAuthenticator myModularRealmAuthenticator = new MyModularRealmAuthenticator();
        myModularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        return myModularRealmAuthenticator;
    }

    /**
     * 下面的代码是添加注解支持，不加这个注解不生效，具体不详
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        //强制指定注解的底层实现使用 cglib 方案
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }

    /**
     * 加入注解的使用，不加入这个注解不生效
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

}
